#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试关键词传递问题
"""

import sys
from crawler.playwright_spider import PlaywrightSpider

def debug_keyword_passing():
    """调试关键词传递"""
    
    keyword = "数据线"
    
    print(f"原始关键词: {keyword}")
    print(f"关键词类型: {type(keyword)}")
    print(f"关键词编码: {keyword.encode('utf-8')}")
    print(f"关键词长度: {len(keyword)}")
    
    # 测试爬虫类的URL构建
    spider = PlaywrightSpider(platform='1688', headless=True)
    
    print(f"\n爬虫平台: {spider.platform}")
    
    # 测试URL构建
    search_url = spider._get_search_url(keyword, 1, True)
    print(f"构建的搜索URL: {search_url}")
    
    # 检查URL中的关键词部分
    from urllib.parse import urlparse, parse_qs
    parsed_url = urlparse(search_url)
    query_params = parse_qs(parsed_url.query)
    
    print(f"\nURL解析结果:")
    print(f"域名: {parsed_url.netloc}")
    print(f"路径: {parsed_url.path}")
    print(f"查询参数: {query_params}")
    
    if 'keywords' in query_params:
        encoded_keyword = query_params['keywords'][0]
        print(f"URL中的编码关键词: {encoded_keyword}")
        
        # 解码测试
        from urllib.parse import unquote
        decoded_keyword = unquote(encoded_keyword)
        print(f"解码后的关键词: {decoded_keyword}")
        print(f"解码后关键词编码: {decoded_keyword.encode('utf-8')}")
        print(f"是否与原始关键词相同: {decoded_keyword == keyword}")
    
    # 测试命令行参数传递
    print(f"\n命令行参数测试:")
    print(f"sys.argv: {sys.argv}")
    
    # 模拟argparse处理
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--keyword', required=False, default=keyword)
    
    # 手动测试
    test_args = ['--keyword', keyword]
    args = parser.parse_args(test_args)
    
    print(f"argparse解析后的关键词: {args.keyword}")
    print(f"argparse解析后关键词类型: {type(args.keyword)}")
    print(f"argparse解析后关键词编码: {args.keyword.encode('utf-8')}")
    print(f"是否与原始关键词相同: {args.keyword == keyword}")

if __name__ == "__main__":
    debug_keyword_passing()